package com.wongoing.sys.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wongoing.annotation.Description;
import com.wongoing.base.PageResult;
import com.wongoing.sys.action.BaseAction;
import com.wongoing.sys.model.SysBasArticle;
import com.wongoing.sys.model.SysCode;
import com.wongoing.sys.model.ext.SysBasArticleExt;
import com.wongoing.sys.model.ext.SysBasColumnExt;
import com.wongoing.sys.service.SysBasArticleService;
import com.wongoing.sys.service.SysBasColumnService;
import com.wongoing.sys.service.SysCodeService;
import com.wongoing.sys.shiro.ShiroUser;
import com.wongoing.sys.viewmodel.JsonResult;
import com.wongoing.util.Constants;
import com.wongoing.util.FileUtil;
import com.wongoing.util.ImageUtil;
import com.wongoing.util.LogService;
import com.wongoing.util.ModelAndViewConstants;
import com.wongoing.util.PageUtil;
import com.wongoing.util.ResourceUtil;
import com.wongoing.util.Status;
import com.wongoing.util.UrlConstants;

@Controller
@RequestMapping("/sys/sysArticleAction")
public class SysBasArticleAction extends BaseAction {
	private SysBasArticleService service;
	private SysBasColumnService columnService;
	private SysCodeService codeService;


	@Autowired
	public void setColumnService(SysBasColumnService columnService) {
		this.columnService = columnService;
	}

	@Autowired
	public void setService(SysBasArticleService service) {
		this.service = service;
	}
	@Autowired
	public void setCodeService(SysCodeService codeService) {
		this.codeService = codeService;
	}

	/**
	 * 功能说明：进入列表显示界面
	 * 修改说明：
	 * @author zhaoxihao
	 * @date 2017年10月15日 下午12:26:19
	 * @param pageSize 每页记录数
	 * @param pageCurrent 当前页索引
	 * @param orderField 排序字段
	 * @param orderDirection 排序方向
	 * @param paramCompanyName 参数字段：文章名称
	 * @param paramRemark 参数字段：备注
	 * @return
	 */
	@RequestMapping(value="/toList")
	public ModelAndView toList(Integer pageSize, Integer pageCurrent, String orderField, String orderDirection,String paramTitle,
			 String paramKeyWords,String paramArticletype) {
		ModelAndView mv = null;
		try {	
			PageResult<SysBasArticleExt> pageResult = PageUtil.pageSet(this.getClass(), pageSize, pageCurrent, orderField, orderDirection);
			pageResult.getParam().put("status", "0");
			//模糊查询判断
			List<Boolean> multiFuzzyQuery = new ArrayList<Boolean>();
		
			if (paramTitle != null && !"".equals(paramTitle)) {
				pageResult.getParam().put("title", paramTitle);
				pageResult.getExt().put("paramTitle", paramTitle);
				multiFuzzyQuery.add(true);
			}else{
				multiFuzzyQuery.add(false);
			}
			if (paramKeyWords != null && !"".equals(paramKeyWords)) {
				pageResult.getParam().put("keyWords", paramKeyWords);
				pageResult.getExt().put("paramKeyWords", paramKeyWords);
				multiFuzzyQuery.add(true);
			}else{
				multiFuzzyQuery.add(false);
			}
			if (paramArticletype != null && !"".equals(paramArticletype)) {
				pageResult.getParam().put("articleType", paramArticletype);
				pageResult.setOrderField("pba.ArticleType");
				pageResult.setOrderDirection("DESC");
				pageResult.getExt().put("paramArticletype", paramArticletype);
				multiFuzzyQuery.add(true);
			}else{
				multiFuzzyQuery.add(false);
			}
			pageResult.setOrderField("pba.RecordTime");
			pageResult.setOrderDirection("DESC");
			pageResult = this.service.getArticleListPageResult(pageResult);
			Map<String,Object> paramOne = new HashMap<String, Object>();
			paramOne.put("status", "0");
			paramOne.put("codeType", "articleType");
	        List<SysCode>  articleType=this.codeService.getByParam(paramOne);
	        SysCode code=new SysCode();
	        code.setCodeName("不限");
	        articleType.add(0,code);
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.PAGE_RESULT, pageResult);
			mv.addObject(ModelAndViewConstants.ARTICLETYPE_MODEL, articleType);
			mv.setViewName(ModelAndViewConstants.ARTICLE_MAIN_VIEW);
			LogService.getInstance(this).debug("获取文章分页数据成功："+ModelAndViewConstants.ARTICLE_MAIN_VIEW);
		}
		catch(Exception ex) {
			LogService.getInstance(this).error("获取文章分页数据失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		return mv;
	}

	/**
	 * 功能说明：进入添加界面操作
	 * 修改说明：
	 * @author zhaoxihao
	 * @date 2017年10月15日 下午12:28:59
	 * @return
	 */
	@RequestMapping(value="/toAdd")
	public ModelAndView toAdd(){
		ModelAndView mv = null;
		try {
			String status = "0";
			List<SysBasColumnExt> treeNodes = this.columnService.getColumnListByParam(status);
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("status", "0");
			params.put("codeType", "signType");
	        List<SysCode>  code=this.codeService.getByParam(params);
	        for (int i = 0; i < code.size(); i++) {  
	        	if (!code.get(i).getCodeType().equals("signType")) {   
	        		code.remove(i);  	  
	        	i--;   	  
	        	}
	        }
	    	Map<String,Object> paramOne = new HashMap<String, Object>();
			paramOne.put("status", "0");
			paramOne.put("codeType", "articleType");
	        List<SysCode>  articleType=this.codeService.getByParam(paramOne);
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.OPERATION_KEY,ModelAndViewConstants.OPERATION_VALUE_ADD);
			mv.addObject(ModelAndViewConstants.TITLE_KEY, "添加文章信息");
			mv.addObject(ModelAndViewConstants.CODE_MODEL, code);
			mv.addObject(ModelAndViewConstants.ARTICLETYPE_MODEL, articleType);
			mv.addObject(ModelAndViewConstants.TREE_NODES_MODEL, OutputJson(treeNodes));
			mv.setViewName(ModelAndViewConstants.ARTICLE_EDIT_VIEW);
			LogService.getInstance(this).error("进入文章添加功能成功：" +ModelAndViewConstants.ARTICLE_EDIT_VIEW);
		}
		catch(Exception ex) {
			LogService.getInstance(this).error("进入文章添加失败：" + ex.getMessage(), ex);
			mv = new ModelAndView("redirect:/error.jsp");
		}
		return mv;
	}
	/**
	 * 功能说明：进入编辑界面
	 * 修改说明：
	 * @author zhaoxihao
	 * @date 2017年10月15日 下午12:29:20
	 * @param id 用户id，主键值
	 * @return
	 */
	@RequestMapping(value="/toEdit")
	public ModelAndView toEdit(Integer id) {
		ModelAndView mv = null;
		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("id", id);
			param.put("status","0");
			String status="0";
			List<SysBasArticleExt> articleList= this.service.getArticleById(param);
			SysBasArticleExt article =articleList.get(0);
			List<SysBasColumnExt> list = this.columnService.getColumnListByParam(status);
			List<SysBasColumnExt> treeNodes = new ArrayList<SysBasColumnExt>();
			for (SysBasColumnExt spe : list) {
				spe.setChecked(false);
				if(article.getClassOne().equals(spe.getId())){
					spe.setChecked(true);
				}
				treeNodes.add(spe);
			}
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("status", "0");
			params.put("codeType", "signType");
	        List<SysCode>  code=this.codeService.getByParam(params);
	        for (int i = 0; i < code.size(); i++) {  
	        	if (!code.get(i).getCodeType().equals("signType")) {   
	        		code.remove(i);  	  
	        	i--;   	  
	        	}
	        }
	    	Map<String,Object> paramOne = new HashMap<String, Object>();
			paramOne.put("status", "0");
			paramOne.put("codeType", "articleType");
	        List<SysCode>  articleType=this.codeService.getByParam(paramOne);
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.OPERATION_KEY,ModelAndViewConstants.OPERATION_VALUE_EDIT);
			mv.addObject(ModelAndViewConstants.TITLE_KEY, "修改文章信息");
			mv.addObject(ModelAndViewConstants.ARTICLE_MODEL, article);
			mv.addObject(ModelAndViewConstants.CODE_MODEL, code);
			mv.addObject(ModelAndViewConstants.ARTICLETYPE_MODEL, articleType);
			mv.addObject(ModelAndViewConstants.TREE_NODES_MODEL, OutputJson(treeNodes));
			mv.setViewName(ModelAndViewConstants.ARTICLE_EDIT_VIEW);
		}
		catch(Exception ex) {
			LogService.getInstance(this).error("进入文章编辑失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		return mv;
	}

	


/**
	 * 功能说明：执行删除操作
	 * 修改说明：
	 * @author zhaoxihao
	 * @date 2017年10月15日 下午12:29:51
	 * @param id 用户id，主键值
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/doDel")
	public Map<String, Object> doDel(Integer id) {
		Map<String, Object> result = null;
		try {
			SysBasArticle entity = new SysBasArticle();
			entity.setId(id);
			entity.setStatus("1");
			int count = this.service.updateByPrimaryKey(entity);
			if (count > 0) {
				LogService.getInstance(this).debug("删除文章信息成功!");
			}
			Integer statusCode = 200;
			String msg = "删除成功!";
			String tabid = tabid(ModelAndViewConstants.SITE_SYS_ID);
			result = JsonResult.jsonReturn(Status.OK.getCode(), msg, tabid,false,"","");
		}
		catch(Exception ex) {
			LogService.getInstance(this).error("删除文章信息[" + id + "]失败：" + ex.getMessage(), ex);
			String msg =  "删除文章信息[" + id + "]失败：" + ex.getMessage();
			result = JsonResult.jsonReturnErr(msg);
		}
		return result;
	}

	
	/**
	 * 
	 * 功能说明： 修改说明：文章信息保存
	 * 
	 * @author zhaoxihao
	 * @date 2017-10-18 上午9:53:47
	 * @param dsType
	 *            数据源类型
	 * @param siteId
	 *            文章Id
	 * @param siteName
	 *            文章名称
	 * @param file
	 *            上传文件
	 * @return
	 */
	@Description("文章信息保存")
	@ResponseBody
	@RequestMapping(value = "/doSave")
	public Map<String, Object> doSave(@RequestParam(value = "dsType", defaultValue = "sysDs") String dsType,
			SysBasArticle entity,  String op,MultipartFile file1,MultipartFile file2,MultipartFile file3) {
		Map<String, Object> jsonResult = null;
		String msg = "";
		try {
			if (file1.getSize() != 0) {
				Map<String, Object> result =  FileUtil.uploadFile(entity.getDownloadUrl(),Constants.UPLOAD_IMG_ARTICLE,file1);
				if (result.get("statusCode") =="300") {
					return result;
				}
				entity.setDownloadUrl((String)result.get("message"));
			}
			if (file2.getSize() != 0) {
				Map<String, Object> result =  FileUtil.uploadVideo(entity.getVideoUrl(),Constants.UPLOAD_IMG_ARTICLE,file2,null,"2");
				if (result.get("statusCode") =="300") {
					return result;
				}
				entity.setVideoUrl((String)result.get("message"));
			}
			if (file3.getSize() != 0) {
				Map<String, Object> result =  ImageUtil.getInstance().uploadImg(entity.getThemeImageUrl(),Constants.UPLOAD_IMG_ARTICLE,file3, "3");
				if (result.get("statusCode") =="300") {
					return result;
				}
				entity.setThemeImageUrl((String)result.get("message"));
			}
			    String tabid = tabid(ModelAndViewConstants.ARTICLE_SYS_ID);
				Date now = new Date();
				ShiroUser currentUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
				entity.setModifyUserId(currentUser.getUserId());
				entity.setModifyUserName(currentUser.getAccount());
				if (null == op || ModelAndViewConstants.OPERATION_VALUE_ADD.equals(op)) {
					entity.setStatus("0");
					int count = this.service.insert(entity);
					if (count > 0) {
						LogService.getInstance(this).debug("添加文章信息成功!");
					}
				} else {
					int count = this.service.updateByPrimaryKey(entity);
					if (count > 0) {
						LogService.getInstance(this).debug("编辑文章信息成功!");
					}
				}
				Integer statusCode = 200;
				String Msg = "文章信息保存成功";
				jsonResult = JsonResult.jsonReturn(statusCode, Msg, tabid);
				return jsonResult;
			
		
		} catch (Exception e) {
			msg = "接口调用异常";
			jsonResult = JsonResult.jsonWsReturn(1, msg, e.getMessage());
			LogService.getInstance(this).error("保存文章信息失败" + e.getMessage());
			String mg =  "保存文章信息失败：" + e.getMessage();
			jsonResult = JsonResult.jsonReturnErr(mg);
			return jsonResult;
		}

	}
	@Description("文章信息保存")
	@ResponseBody
	@RequestMapping(value = "/doSaveImage")
	public void doSaveImage(HttpServletRequest request, HttpServletResponse response,@RequestParam MultipartFile upload) {
		Map<String, Object> jsonResult = null;
		String msg = "";
		//"http://localhost:8080/pass/"
		String url=UrlConstants.BASE_URL;
		try {
			response.setCharacterEncoding("UTF-8"); 
			 PrintWriter out=null; 
			 try { 
			  out = response.getWriter(); 
			 } catch (IOException e1) { 
			  e1.printStackTrace(); 
			 } 
			 String callback = request.getParameter("CKEditorFuncNum"); 
			    
			 // 获得response,request 
			 Map<String, Object> m = new HashMap<String, Object>(); 
			    
			 if (!ServletFileUpload.isMultipartContent(request)) { 
			  m.put("error", 1); 
			  m.put("message", "请选择文件!"); 
			  //return m; 
			 } 
			    
			 String originalFileName=null;//上传的图片文件名 
			 String fileExtensionName=null;//上传图片的文件扩展名 
			  if (upload.getSize()> 2*1024* 1024) { 
			   out.println("<script type=\"text/javascript\">"); 
			   out.println("window.parent.CKEDITOR.tools.callFunction(" + callback 
			      + ",''," + "'文件大小不得大于2M');"); 
			   out.println("</script>"); 
			      
			  } 
			  else {
			  originalFileName=upload.getOriginalFilename(); 
			  System.out.println("上传的图片文件名="+originalFileName); 
			  fileExtensionName= originalFileName.substring( 
			  originalFileName.lastIndexOf(".") ,originalFileName.length()).toLowerCase(); 
			  System.out.println("图片文件扩展名="+fileExtensionName); 
			  
			if (upload.getSize() != 0) {
				Map<String, Object> result =  ImageUtil.getInstance().uploadImg("",Constants.UPLOAD_IMG_ESSAY,upload,"1");
				if (result.get("statusCode") =="300") {
				   out.println("<script type=\"text/javascript\">"); 
				   out.println("window.parent.CKEDITOR.tools.callFunction(" + callback 
				      + ",''," +result.get("message")+");"); 
				   out.println("</script>"); 
				}
				String s=(String)result.get("message");
				String s1 =s.replace('\\','/');
				String imageUrl=url+s1;
			//	String s="http://localhost:8080/pass/upload/img/site/site_20171031084915.jpg";
				   // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url 
				   out.println("<script type=\"text/javascript\">"); 
				   out.println("window.parent.CKEDITOR.tools.callFunction(" + callback 
				      + ",'" +imageUrl + "','')"); 
				   out.println("</script>"); 
			}
			  }
		} catch (Exception e) {
			msg = "接口调用异常";
			jsonResult = JsonResult.jsonValidateReturn(false,e.getMessage());
			LogService.getInstance(this).error("保存文章信息失败" + e.getMessage());
		/*	return jsonResult;*/
		}

	}
	/**
	 * 
	 * 功能说明：推送消息
	 * 修改说明：
	 * @author zhaoxihao
	 * @date 2017-8-25 下午5:23:03
	 * @param pushId	推送id
	 * @param paramCustomerName	客户名称
	 * @param paramCustomerMobile	客户电话
	 * @param paramReadTime	阅读时间
	 * @param paramPushTime	推送时间
	 * @return
	 */

	@RequestMapping(value = "/toDetails")
	public ModelAndView toDetails(Integer id) 
			throws IllegalAccessException, NoSuchMethodException {
	
		ModelAndView mv = null;
		try {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", id);
		param.put("status","0");
		List<SysBasArticleExt> articleList= this.service.getArticleById(param);
		mv = new ModelAndView();
        mv.addObject(ModelAndViewConstants.ARTICLE_MODEL, articleList.get(0));
		mv.setViewName(ModelAndViewConstants.ARTKICLE_DETAILS_VIEW);
		LogService.getInstance(this).debug("获取文章详情数据成功："+ModelAndViewConstants.ARTKICLE_DETAILS_VIEW);
		}
		catch(Exception ex) {
			LogService.getInstance(this).error("获取文章详情数据失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
	
		return mv;
	}
	  
	
}
